import { Base64 } from 'js-base64'

let isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Adr') > -1;
let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

// dev为true时不调用基座能力 方便在web上开发

let dev = false

//这是必须要写的，用来创建一些设置
function setupWebViewJavascriptBridge(callback) {
    if (dev) return

    //Android使用
    if (isAndroid) {
        if (window.WebViewJavascriptBridge) {
            callback(window.WebViewJavascriptBridge);
        } else {
            document.addEventListener(
                'WebViewJavascriptBridgeReady',
                () => {
                    callback(window.WebViewJavascriptBridge);
                },
                false
            );
        }
        // console.log('tag', '安卓');
        sessionStorage.phoneType = 'android';
    }

    //iOS使用
    if (isiOS) {
        if (window.WebViewJavascriptBridge) {
            return callback(window.WebViewJavascriptBridge);
        }
        if (window.WVJBCallbacks) {
            return window.WVJBCallbacks.push(callback);
        }
        window.WVJBCallbacks = [callback];
        var WVJBIframe = document.createElement('iframe');
        WVJBIframe.style.display = 'none';
        WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(() => {
            document.documentElement.removeChild(WVJBIframe);
        }, 0);
        console.log('tag', 'ios');
        sessionStorage.phoneType = 'ios';
    }
}

//注册回调函数，第一次连接时调用 初始化函数(android需要初始化,ios不用)
setupWebViewJavascriptBridge((bridge) => {
    if (dev) return

    if (isAndroid) {
        //初始化
        bridge.init((message, responseCallback) => {
            var data = {
                'Javascript Responds': 'Wee!'
            };
            responseCallback(data);
        });
    }
});

function createFuncName() {
    return `iosCallBack_${Date.now()}_${Math.ceil(Math.random() * 10)}`
}


/**
 * 
 * @param {*} _props { name: ios function name, data: data passed to ios, callback: ios callback function }
 */
function jsCallIos(_props) {
    let callbackName = createFuncName()
    window[callbackName] = (res) => {
        const result = Base64.decode(res)
        _props.callback(result)
    }

    window.webkit?.messageHandlers?.callHandler?.postMessage({
        name: _props.name,
        data: Base64.encode(JSON.stringify(_props.data)),
        callbackName,
    })
}
function jsCallIosRegisterHandler(_props) {
    let callbackName = _props.name
    window[callbackName] = (res) => {
        const result = res
        _props.callback(result)
    }

    window.webkit?.messageHandlers?.callHandler?.postMessage({
        name: _props.name,
        data: _props.data,
        callbackName,
    })
}

export default {
    // js调APP方法 （参数分别为:app提供的方法名  传给app的数据  回调）
    callHandler(name, data, callback) {
        if (!dev) {
            if (isAndroid) {
                setupWebViewJavascriptBridge((bridge) => {
                    bridge.callHandler(name, data, callback);
                });
            }
            if (isiOS) {
                jsCallIos({
                    name,
                    data,
                    callback
                })
            }
        }
    },

    // APP调js方法 （参数分别为:js提供的方法名  回调）
    registerHandler(name, callback) {
        if (!dev) {
            if (isAndroid) {
                setupWebViewJavascriptBridge((bridge) => {
                    console.log(bridge)
                    bridge.registerHandler(name, (data, responseCallback) => {
                        callback(data, responseCallback);
                    });
                });
            }
            if (isiOS) {
                jsCallIosRegisterHandler({
                    name,
                    callback
                })
            }
        }
    },

    isDev() {
        return dev
    }
};